using System;
using System.Collections.Generic;
using System.Text;

namespace CoreCalc.SheetDefinedFunctions
{
  class MakeNonCodeGenFunction
  {
    public static void CreateStandardFunction(string name, FullCellAddr[] inputCells, FullCellAddr output)
    {
      new Function(name.ToUpper(),
                   delegate(Sheet sheet2, Expr[] es2, int col2, int row2)
                   {
                     if (es2.Length != inputCells.Length)
                       return new ErrorValue("ARGCOUNT");

                     List<Value> values = new List<Value>();

                     foreach (Expr expr in es2)
                     {
                       values.Add(expr.Eval(sheet2, col2, row2));
                     }

                     for (int i = 0; i < values.Count; i++)
                     {
                       //Create Cell
                       Cell newCell;
                       Value currentVal = values[i];

                       TextValue txtVal = currentVal as TextValue;
                       if (txtVal != null)
                       {
                         newCell = new TextCell(txtVal.value);
                       }
                       else
                       {
                         NumberValue numVal = currentVal as NumberValue;
                         if (numVal != null)
                           newCell = new NumberCell(numVal.value);
                         else
                           return new ErrorValue("ARGTYPE");
                       }

                       FullCellAddr currentAddr = inputCells[i];

                       currentAddr.sheet[currentAddr.col, currentAddr.row] = newCell;
                     }
                     // sestoft: what's this??? who knows whether it preserves CoreCalc sheet invariants
                     Cell.forceEval = true;
                     Value back = output.Eval();
                     Cell.forceEval = false;
                     return back;
                   });
    }
  }
}
